{% extends 'base.html' %}
{% load static %}

{% block title %}模板详情 - {{ template.name }} - CFS Web System{% endblock %}

{% block page_type %}template-detail{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item"><a href="{% url 'dashboard:dashboard' %}">仪表板</a></li>
<li class="breadcrumb-item"><a href="{% url 'template_management:template_list' %}">模板列表</a></li>
<li class="breadcrumb-item active">{{ template.name }}</li>
{% endblock %}

{% block content %}
<div class="row">
    <!-- 模板基本信息 -->
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="fas fa-file-alt me-2"></i>{{ template.name }}
                        <span class="badge bg-{{ template.is_active|yesno:'success,warning' }} ms-2">
                            {{ template.is_active|yesno:'启用,禁用' }}
                        </span>
                    </h5>
                    <div class="btn-group">
                        <a href="{% url 'template_management:template_edit' template.id %}" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-edit"></i> 编辑
                        </a>

                                           </a>
                        <div class="btn-group">
                            <button type="button" class="btn btn-outline-secondary btn-sm dropdown-toggle" data-bs-toggle="dropdown">
                                <i class="fas fa-ellipsis-v"></i>
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="#" onclick="exportTemplate()"><i class="fas fa-download me-2"></i>导出模板</a></li>
                                <li><a class="dropdown-item" href="#" onclick="shareTemplate()"><i class="fas fa-share me-2"></i>分享模板</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item text-danger" href="#" onclick="deleteTemplate()"><i class="fas fa-trash me-2"></i>删除模板</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <!-- 模板描述 -->
                {% if template.description %}
                <div class="mb-4">
                    <h6>描述</h6>
                    <p class="text-muted">{{ template.description }}</p>
                </div>
                {% endif %}
                
                <!-- 模板配置 -->
                <div class="mb-4">
                    <h6>配置信息</h6>
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr><td>创建时间:</td><td>{{ template.created_at|date:'Y-m-d H:i' }}</td></tr>
                                <tr><td>更新时间:</td><td>{{ template.updated_at|date:'Y-m-d H:i' }}</td></tr>
                                <tr><td>使用次数:</td><td>{{ template.usage_count }}</td></tr>
                                <tr><td>创建者:</td><td>{{ template.created_by.username|default:'系统' }}</td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr><td>配置字段:</td><td>{{ template.field_configs|length }} 个</td></tr>
                                <tr><td>输出格式:</td><td>{{ output_format|upper }}</td></tr>
                                <tr><td>文件类型:</td><td>{{ file_type|default:'通用' }}</td></tr>
                                <tr><td>版本:</td><td>v{{ template.version|default:'1.0' }}</td></tr>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- 数据源配置 -->
                <div class="mb-4">
                    <div class="mb-3">
                        <h6><i class="fas fa-database me-2"></i>数据源配置</h6>
                    </div>
                    <div id="data-sources-container">
                        <!-- 数据源配置将通过JavaScript动态渲染 -->
                    </div>
                </div>
                
                <!-- 处理规则 -->
                <div class="mb-4">
                    <div class="mb-3">
                        <h6><i class="fas fa-cogs me-2"></i>处理规则</h6>
                    </div>
                    <div id="processing-rules-container">
                        <!-- 处理规则将通过JavaScript动态渲染 -->
                    </div>
                </div>
                
                <!-- 输出配置 -->
                <div class="mb-4">
                    <div class="mb-3">
                        <h6><i class="fas fa-file-export me-2"></i>输出配置</h6>
                    </div>
                    <div id="output-configs-container">
                        <!-- 输出配置将通过JavaScript动态渲染 -->
                    </div>
                </div>
                
                <!-- 处理逻辑 -->
                {% if template.processing_logic %}
                <div class="mb-4">
                    <h6>处理逻辑</h6>
                    <div class="bg-light p-3 rounded">
                        <pre class="mb-0"><code>{{ template.processing_logic }}</code></pre>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
    
    <!-- 侧边栏 -->
    <div class="col-lg-4">
        <!-- 使用统计 -->
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-chart-bar me-2"></i>使用统计
                </h6>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6">
                        <div class="stat-item">
                            <div class="stat-value text-primary">{{ template.usage_count }}</div>
                            <div class="stat-label">总使用次数</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="stat-item">
                            <div class="stat-value text-success" id="success-rate">--</div>
                            <div class="stat-label">成功率</div>
                        </div>
                    </div>
                </div>
                
                <hr>
                
                <div class="row text-center">
                    <div class="col-6">
                        <div class="stat-item">
                            <div class="stat-value text-info" id="avg-processing-time">--</div>
                            <div class="stat-label">平均处理时间</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="stat-item">
                            <div class="stat-value text-warning" id="last-used">--</div>
                            <div class="stat-label">最后使用</div>
                        </div>
                    </div>
                </div>
                
                <!-- 使用趋势图 -->
                <div class="mt-4">
                    <h6>使用趋势</h6>
                    <canvas id="usageTrendChart" style="height: 200px; max-height: 200px;"></canvas>
                </div>
            </div>
        </div>
        
        
        <!-- 模板信息 -->
        <div class="card mt-4">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-info-circle me-2"></i>模板信息
                </h6>
            </div>
            <div class="card-body">
                <div class="template-info">
                    <div class="info-item">
                        <div class="info-label">模板ID</div>
                        <div class="info-value"><code>{{ template.id }}</code></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">文件路径</div>
                        <div class="info-value"><small>{{ template.file_path|default:'未设置' }}</small></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">配置哈希</div>
                        <div class="info-value"><small>{{ template.config_hash|default:'未计算' }}</small></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">最后验证</div>
                        <div class="info-value"><small>{{ template.last_validated|date:'Y-m-d H:i'|default:'从未' }}</small></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 配置字段编辑模态框 -->
<div class="modal fade" id="configFieldModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-cog me-2"></i><span id="field-modal-title">添加配置字段</span>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="config-field-form">
                    <div class="mb-3">
                        <label class="form-label">字段名 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="field-name" required>
                        <div class="form-text">字段的唯一标识符，只能包含字母、数字和下划线</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">显示名称</label>
                        <input type="text" class="form-control" id="field-label">
                        <div class="form-text">在界面上显示的字段名称</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">字段类型</label>
                        <select class="form-select" id="field-type">
                            <option value="text">文本</option>
                            <option value="number">数字</option>
                            <option value="select">下拉选择</option>
                            <option value="checkbox">复选框</option>
                            <option value="textarea">多行文本</option>
                            <option value="file">文件</option>
                            <option value="date">日期</option>
                        </select>
                    </div>
                    
                    <div class="mb-3" id="field-options-group" style="display: none;">
                        <label class="form-label">选项</label>
                        <textarea class="form-control" id="field-options" rows="3" placeholder="每行一个选项，格式：值|显示文本"></textarea>
                        <div class="form-text">例如：value1|选项1</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">默认值</label>
                        <input type="text" class="form-control" id="field-default">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" id="field-description" rows="2"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="field-required">
                            <label class="form-check-label" for="field-required">
                                必填字段
                            </label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveConfigField()">
                    <i class="fas fa-save"></i> 保存
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 模板测试模态框 -->
<div class="modal fade" id="templateTestModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-vial me-2"></i>模板测试
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="test-form-container">
                    <!-- 测试表单将动态生成 -->
                </div>
                
                <div id="test-result-container" style="display: none;">
                    <h6>测试结果</h6>
                    <div id="test-result-content">
                        <!-- 测试结果将显示在这里 -->
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="runTemplateTest()" id="run-test-btn">
                    <i class="fas fa-play"></i> 运行测试
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="{% static 'js/chart.min.js' %}"></script>
<script>
// 页面状态
const templateId = '{{ template.id }}';
let usageTrendChart = null;
let currentEditingField = null;

// 配置数据
const dataSources = {{ data_sources_json|safe }};
const processingRules = {{ processing_rules_json|safe }};
const outputConfigs = {{ output_configs_json|safe }};
const templateFieldConfigs = {{ template.field_configs|default:"{}"|safe }};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeTemplatePage();
});

// 初始化模板详情页面
function initializeTemplatePage() {
    // 渲染数据源配置
    renderDataSources();
    
    // 渲染处理规则
    renderProcessingRules();
    
    // 渲染输出配置
    renderOutputConfigs();
    
    // 加载使用统计
    loadUsageStats();
    
    // 初始化使用趋势图
    initUsageTrendChart();
    
    // 绑定事件
    bindEvents();
}

// 渲染数据源配置
function renderDataSources() {
    const container = document.getElementById('data-sources-container');
    
    if (!dataSources || dataSources.length === 0) {
        container.innerHTML = '<p class="text-muted">暂无数据源配置</p>';
        return;
    }
    
    let html = '';
    dataSources.forEach((source, index) => {
        html += `
            <div class="card mb-3">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="card-title">
                                <i class="fas fa-file-${getFileIcon(source.source_type)} me-2"></i>
                                ${source.source_name || '数据源' + (index + 1)}
                            </h6>
                            <p class="text-muted mb-2">${getSourceTypeText(source.source_type)}</p>
                        </div>
                        <div class="col-md-6">
                            <small class="text-muted">
                                <div><strong>读取方向:</strong> ${getReadDirectionText(source.read_direction)}</div>
                                <div><strong>排序:</strong> ${source.source_order}</div>
                                ${source.header_config && source.header_config.has_header ? '<div><strong>包含表头:</strong> 是</div>' : ''}
                            </small>
                        </div>
                    </div>
                    ${source.data_range ? `
                        <div class="mt-2">
                            <small class="text-muted">
                                <strong>数据范围:</strong> 
                                行 ${source.data_range.start_row || 1} - ${source.data_range.end_row === -1 ? '末尾' : source.data_range.end_row}
                                ${source.data_range.columns && source.data_range.columns.length > 0 ? ', 列: ' + source.data_range.columns.join(', ') : ''}
                            </small>
                        </div>
                    ` : ''}
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 渲染处理规则
function renderProcessingRules() {
    const container = document.getElementById('processing-rules-container');
    
    if (!processingRules || processingRules.length === 0) {
        container.innerHTML = '<p class="text-muted">暂无处理规则</p>';
        return;
    }
    
    let html = '';
    processingRules.forEach((rule, index) => {
        html += `
            <div class="card mb-3">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-8">
                            <h6 class="card-title">
                                <i class="fas fa-${getRuleIcon(rule.rule_type)} me-2"></i>
                                ${rule.rule_name || '规则' + (index + 1)}
                            </h6>
                            <p class="text-muted mb-2">${getRuleTypeText(rule.rule_type)}</p>
                        </div>
                        <div class="col-md-4 text-end">
                            <span class="badge bg-primary">顺序: ${rule.rule_order}</span>
                        </div>
                    </div>
                    ${rule.rule_config ? `
                        <div class="mt-2">
                            <small class="text-muted">
                                ${formatRuleConfig(rule.rule_config, rule.rule_type)}
                            </small>
                        </div>
                    ` : ''}
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 渲染输出配置
function renderOutputConfigs() {
    const container = document.getElementById('output-configs-container');
    
    if (!outputConfigs || outputConfigs.length === 0) {
        container.innerHTML = '<p class="text-muted">暂无输出配置</p>';
        return;
    }
    
    let html = '';
    outputConfigs.forEach((config, index) => {
        html += `
            <div class="card mb-3">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="card-title">
                                <i class="fas fa-file-${getFileIcon(config.output_format)} me-2"></i>
                                ${config.output_name || '输出' + (index + 1)}
                            </h6>
                            <p class="text-muted mb-2">${getOutputTypeText(config.output_type)} - ${config.output_format.toUpperCase()}</p>
                        </div>
                        <div class="col-md-6">
                            <small class="text-muted">
                                ${config.filename_template ? `<div><strong>文件名模板:</strong> ${config.filename_template}</div>` : ''}
                                ${config.output_config && config.output_config.sheet_name ? `<div><strong>工作表:</strong> ${config.output_config.sheet_name}</div>` : ''}
                                ${config.output_config && config.output_config.include_header ? '<div><strong>包含表头:</strong> 是</div>' : ''}
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 绑定事件
function bindEvents() {
    // 字段类型变化事件
    const fieldTypeEl = document.getElementById('field-type');
    if (fieldTypeEl) {
        fieldTypeEl.addEventListener('change', function() {
            toggleFieldOptions(this.value);
        });
    }
}

// 加载使用统计
function loadUsageStats() {
    // 使用模拟数据，因为API端点可能还没有实现
    const mockStats = {
        success_rate: 100,
        avg_processing_time: '0ms',
        last_used: null
    };
    
    updateUsageStats(mockStats);
}

// 更新使用统计
function updateUsageStats(stats) {
    const successRateEl = document.getElementById('success-rate');
    const avgTimeEl = document.getElementById('avg-processing-time');
    const lastUsedEl = document.getElementById('last-used');
    
    if (successRateEl) {
        successRateEl.textContent = (stats.success_rate || 0) + '%';
    }
    if (avgTimeEl) {
        avgTimeEl.textContent = stats.avg_processing_time || '--';
    }
    if (lastUsedEl) {
        lastUsedEl.textContent = stats.last_used ? CFS.utils.formatDateTime(stats.last_used) : '从未';
    }
}


// 初始化使用趋势图
function initUsageTrendChart() {
    const ctx = document.getElementById('usageTrendChart').getContext('2d');
    
    // 使用模拟数据创建趋势图
    const mockTrendData = {
        labels: ['本周一', '本周二', '本周三', '本周四', '本周五', '本周六', '本周日'],
        data: [0, 0, 0, 0, 0, 0, 0]
    };
    
    createUsageTrendChart(ctx, mockTrendData);
}

// 创建使用趋势图
function createUsageTrendChart(ctx, trendData) {
    usageTrendChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: trendData.labels || [],
            datasets: [{
                label: '使用次数',
                data: trendData.data || [],
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
}

// 添加配置字段
function addConfigField() {
    currentEditingField = null;
    document.getElementById('field-modal-title').textContent = '添加配置字段';
    clearFieldForm();
    
    const modal = new bootstrap.Modal(document.getElementById('configFieldModal'));
    modal.show();
}

// 编辑配置字段
function editConfigField(fieldName) {
    currentEditingField = fieldName;
    document.getElementById('field-modal-title').textContent = '编辑配置字段';
    
    // 加载字段配置
    fetch(`/template-management/api/templates/${templateId}/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                fillFieldForm(data.field);
                const modal = new bootstrap.Modal(document.getElementById('configFieldModal'));
                modal.show();
            } else {
                CFS.utils.showNotification('加载字段配置失败: ' + data.error, 'error');
            }
        })
        .catch(error => {
            CFS.utils.showNotification('加载字段配置失败: ' + error.message, 'error');
        });
}

// 删除配置字段
async function deleteConfigField(fieldName) {
    const confirmed = await showConfirm(
        `确定要删除字段 "${fieldName}" 吗？此操作不可恢复。`,
        '删除字段确认',
        '删除',
        '取消'
    );
    
    if (!confirmed) {
        return;
    }
    
    fetch(`/template-management/api/templates/${templateId}/`, {
        method: 'DELETE',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('字段已删除', 'success');
            location.reload(); // 重新加载页面
        } else {
            CFS.utils.showNotification('删除失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        CFS.utils.showNotification('删除失败: ' + error.message, 'error');
    });
}

// 保存配置字段
function saveConfigField() {
    const formData = {
        name: document.getElementById('field-name').value.trim(),
        label: document.getElementById('field-label').value.trim(),
        type: document.getElementById('field-type').value,
        default: document.getElementById('field-default').value.trim(),
        description: document.getElementById('field-description').value.trim(),
        required: document.getElementById('field-required').checked
    };
    
    // 验证字段名
    if (!formData.name) {
        CFS.utils.showNotification('请输入字段名', 'warning');
        return;
    }
    
    if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(formData.name)) {
        CFS.utils.showNotification('字段名只能包含字母、数字和下划线，且不能以数字开头', 'warning');
        return;
    }
    
    // 处理选项
    if (formData.type === 'select') {
        const optionsText = document.getElementById('field-options').value.trim();
        if (optionsText) {
            formData.options = optionsText.split('\n').map(line => {
                const parts = line.split('|');
                return {
                    value: parts[0].trim(),
                    label: parts[1] ? parts[1].trim() : parts[0].trim()
                };
            });
        }
    }
    
    const url = currentEditingField ? 
        `/template-management/api/templates/${templateId}/` :
        `/template-management/api/templates/${templateId}/`;
    
    const method = currentEditingField ? 'PUT' : 'POST';
    
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': CFS.utils.getCsrfToken()
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('字段已保存', 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('configFieldModal'));
            modal.hide();
            
            // 重新加载页面
            location.reload();
        } else {
            CFS.utils.showNotification('保存失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        CFS.utils.showNotification('保存失败: ' + error.message, 'error');
    });
}

// 清空字段表单
function clearFieldForm() {
    document.getElementById('field-name').value = '';
    document.getElementById('field-label').value = '';
    document.getElementById('field-type').value = 'text';
    document.getElementById('field-default').value = '';
    document.getElementById('field-description').value = '';
    document.getElementById('field-required').checked = false;
    document.getElementById('field-options').value = '';
    toggleFieldOptions('text');
}

// 填充字段表单
function fillFieldForm(field) {
    document.getElementById('field-name').value = field.name || '';
    document.getElementById('field-label').value = field.label || '';
    document.getElementById('field-type').value = field.type || 'text';
    document.getElementById('field-default').value = field.default || '';
    document.getElementById('field-description').value = field.description || '';
    document.getElementById('field-required').checked = field.required || false;
    
    if (field.options) {
        const optionsText = field.options.map(opt => `${opt.value}|${opt.label}`).join('\n');
        document.getElementById('field-options').value = optionsText;
    }
    
    toggleFieldOptions(field.type || 'text');
}

// 切换字段选项显示
function toggleFieldOptions(fieldType) {
    const optionsGroup = document.getElementById('field-options-group');
    optionsGroup.style.display = fieldType === 'select' ? 'block' : 'none';
}



// 使用模板
function useTemplate() {
    window.location.href = `/data-generation/?template=${templateId}`;
}

// 导出模板
function exportTemplate() {
    window.open(`/template-management/templates/${templateId}/export/`, '_blank');
}

// 分享模板
function shareTemplate() {
    // 实现模板分享功能
    console.log('分享模板:', templateId);
}

// 删除模板
async function deleteTemplate() {
    const confirmed = await showConfirm(
        '确定要删除这个模板吗？此操作不可恢复。',
        '删除模板确认',
        '删除',
        '取消'
    );
    
    if (!confirmed) {
        return;
    }
    
    fetch(`/template-management/api/templates/${templateId}/`, {
        method: 'DELETE',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('模板已删除', 'success');
            window.location.href = '/template-management/templates/';
        } else {
            CFS.utils.showNotification('删除失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        CFS.utils.showNotification('删除失败: ' + error.message, 'error');
    });
}

// 测试模板
function testTemplate() {
    // 生成测试表单
    generateTestForm();
    
    const modal = new bootstrap.Modal(document.getElementById('templateTestModal'));
    modal.show();
}

// 生成测试表单
function generateTestForm() {
    const container = document.getElementById('test-form-container');
    
    // 这里应该根据模板配置字段生成表单
    // 简化实现
    container.innerHTML = `
        <div class="mb-3">
            <label class="form-label">测试数据文件</label>
            <input type="file" class="form-control" id="test-file" accept=".xlsx,.xls,.csv">
            <div class="form-text">选择一个测试文件来验证模板配置</div>
        </div>
        
        <div class="mb-3">
            <label class="form-label">测试模式</label>
            <select class="form-select" id="test-mode">
                <option value="validate">验证配置</option>
                <option value="preview">预览输出</option>
                <option value="full">完整测试</option>
            </select>
        </div>
    `;
}

// 运行模板测试
function runTemplateTest() {
    const testFile = document.getElementById('test-file').files[0];
    const testMode = document.getElementById('test-mode').value;
    
    if (!testFile) {
        CFS.utils.showNotification('请选择测试文件', 'warning');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', testFile);
    formData.append('mode', testMode);
    
    const runTestBtn = document.getElementById('run-test-btn');
    runTestBtn.disabled = true;
    runTestBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 测试中...';
    
    fetch(`/template-management/api/test/output/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showTestResult(data.result);
        } else {
            showTestResult({ error: data.error });
        }
    })
    .catch(error => {
        showTestResult({ error: error.message });
    })
    .finally(() => {
        runTestBtn.disabled = false;
        runTestBtn.innerHTML = '<i class="fas fa-play"></i> 运行测试';
    });
}

// 显示测试结果
function showTestResult(result) {
    const container = document.getElementById('test-result-container');
    const content = document.getElementById('test-result-content');
    
    if (result.error) {
        content.innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle me-2"></i>
                测试失败: ${result.error}
            </div>
        `;
    } else {
        content.innerHTML = `
            <div class="alert alert-success">
                <i class="fas fa-check-circle me-2"></i>
                测试通过
            </div>
            <div class="mt-3">
                <h6>测试详情</h6>
                <pre class="bg-light p-3 rounded">${JSON.stringify(result, null, 2)}</pre>
            </div>
        `;
    }
    
    container.style.display = 'block';
}

// 验证模板
function validateTemplate() {
    fetch(`/template-management/api/templates/${templateId}/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (data.valid) {
                CFS.utils.showNotification('模板配置有效', 'success');
            } else {
                CFS.utils.showNotification('模板配置无效: ' + data.errors.join(', '), 'error');
            }
        } else {
            CFS.utils.showNotification('验证失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        CFS.utils.showNotification('验证失败: ' + error.message, 'error');
    });
}

// 预览输出
function previewOutput() {
    // 实现输出预览功能
    console.log('预览输出:', templateId);
}



// 查看任务详情
function viewTaskDetail(taskId) {
    window.open(`/task-status/?task=${taskId}`, '_blank');
}

// 预览文件
function previewFile(fileId) {
    window.open(`/file-manager/preview/${fileId}/`, '_blank');
}

// 下载文件
function downloadFile(fileId) {
    window.open(`/file-manager/download/${fileId}/`, '_blank');
}

// 工具函数
function getTaskStatusColor(status) {
    const colors = {
        'pending': 'secondary',
        'running': 'primary',
        'completed': 'success',
        'failed': 'danger',
        'cancelled': 'warning'
    };
    return colors[status] || 'secondary';
}

function getTaskStatusText(status) {
    const texts = {
        'pending': '等待中',
        'running': '处理中',
        'completed': '已完成',
        'failed': '失败',
        'cancelled': '已取消'
    };
    return texts[status] || '未知';
}

function getFileIcon(extension) {
    const icons = {
        'xlsx': 'excel text-success',
        'xls': 'excel text-success', 
        'excel': 'excel text-success',
        'csv': 'csv text-info',
        'txt': 'alt text-secondary'
    };
    return icons[extension.toLowerCase()] || 'alt text-muted';
}

// 获取数据源类型文本
function getSourceTypeText(sourceType) {
    const types = {
        'excel': 'Excel文件',
        'csv': 'CSV文件',
        'txt': '文本文件',
        'database': '数据库',
        'api': 'API接口'
    };
    return types[sourceType] || sourceType;
}

// 获取读取方向文本
function getReadDirectionText(direction) {
    const directions = {
        'horizontal': '水平读取',
        'vertical': '垂直读取'
    };
    return directions[direction] || direction;
}

// 获取规则类型图标
function getRuleIcon(ruleType) {
    const icons = {
        'field_mapping': 'exchange-alt',
        'data_transform': 'magic',
        'validation': 'check-circle',
        'filter': 'filter',
        'aggregate': 'calculator',
        'split': 'cut'
    };
    return icons[ruleType] || 'cog';
}

// 获取规则类型文本
function getRuleTypeText(ruleType) {
    const types = {
        'field_mapping': '字段映射',
        'data_transform': '数据转换',
        'validation': '数据验证',
        'filter': '数据过滤',
        'aggregate': '数据聚合',
        'split': '数据拆分'
    };
    return types[ruleType] || ruleType;
}

// 格式化规则配置
function formatRuleConfig(config, ruleType) {
    if (!config) return '';
    
    let html = '';
    
    switch (ruleType) {
        case 'field_mapping':
            if (config.mapping_rules) {
                html += '<div><strong>映射规则:</strong></div>';
                Object.entries(config.mapping_rules).forEach(([target, source]) => {
                    html += `<div class="ms-2">${source} → ${target}</div>`;
                });
            }
            break;
        case 'data_transform':
            if (config.transform_type) {
                html += `<div><strong>转换类型:</strong> ${config.transform_type}</div>`;
            }
            break;
        case 'validation':
            if (config.validation_rules) {
                html += '<div><strong>验证规则:</strong></div>';
                config.validation_rules.forEach(rule => {
                    html += `<div class="ms-2">${rule.field}: ${rule.rule}</div>`;
                });
            }
            break;
        default:
            // 显示通用配置信息
            Object.entries(config).forEach(([key, value]) => {
                if (typeof value === 'object') {
                    html += `<div><strong>${key}:</strong> ${JSON.stringify(value)}</div>`;
                } else {
                    html += `<div><strong>${key}:</strong> ${value}</div>`;
                }
            });
    }
    
    return html;
}

// 获取输出类型文本
function getOutputTypeText(outputType) {
    const types = {
        'single_file': '单文件输出',
        'multi_file': '多文件输出',
        'database': '数据库输出',
        'api': 'API输出'
    };
    return types[outputType] || outputType;
}

// 显示确认对话框
function showConfirm(message, title = '确认操作', confirmText = '确定', cancelText = '取消') {
    return new Promise((resolve) => {
        const modalId = 'confirm-modal-' + Date.now();
        const modalHtml = `
            <div class="modal fade" id="${modalId}" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">${title}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <p>${message}</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">${cancelText}</button>
                            <button type="button" class="btn btn-danger confirm-btn">${confirmText}</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        const modal = new bootstrap.Modal(document.getElementById(modalId));
        
        document.querySelector(`#${modalId} .confirm-btn`).addEventListener('click', () => {
            document.getElementById(modalId).dataset.resolved = 'true';
            modal.hide();
            resolve(true);
        });
        
        document.getElementById(modalId).addEventListener('hidden.bs.modal', function() {
            if (!this.dataset.resolved) {
                resolve(false);
            }
            this.remove();
        });
        
        modal.show();
    });
}
</script>
{% endblock %}